home *** CD-ROM | disk | FTP | other *** search
- Path: locutus.rchland.ibm.com!usenet
- From: Philip Staite <pstaite+@rchland.ibm.com>
- Newsgroups: comp.lang.c++
- Subject: Re: random numbers in visual C++
- Date: Thu, 07 Mar 1996 07:40:20 -0600
- Organization: IBM Rochester, MN
- Message-ID: <313EE744.2781@rchland.ibm.com>
- References: <4hfusd$916@eddie.intr.net>
- NNTP-Posting-Host: powertool.rchland.ibm.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (X11; I; AIX 1)
-
- willodk@intr.net wrote:
- >
- > How can I generate random numbers in Visual C++ (version 1.52) between 0 and 100? How is the RAND_MAX
- > set?
-
- Try this:
-
-
- #include<stdlib.h>
- #include<time.h>
-
-
- // one time initialization somewhere in your code
- srand( time( 0 ) );
-
-
- //
- // gen rand number between lo and hi (inclusive)
- //
- int rangen( int lo, int hi );
-
-
- int rangen( int lo, int hi ) {
- return lo + ( rand() % ( hi - lo + 1 ) ); }
-
-
- Then you could call this function as:
-
- int myrand = rangen( 0, 100 );
-
- Which would give you numbers between 0 and 100 inclusive.
-
- Before any other comp-sci types jump on this, yes, most system supplied
- rand()'s are not that great at producing good _sequences_ of random
- numbers. And yes, simple modulo is not a good way to map down
- 0..RAND_MAX to lo..hi -- but it's quick and easy ;-)
-
-
-
- --
-
- Phil Staite, (507) 253-2529, team OS/2
- internet: pstaite@vnet.ibm.com internal: pstaite@rchland
-